import React, { Component } from "react";
import { removeAllProps } from '../actions/application'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { withRouter, matchPath } from 'react-router'

const validate = function(history) {
  const isLoggedIn = !!window.localStorage.getItem("uid");
  if (!isLoggedIn && history.location.pathname != "/login") {
    history.replace("/login");
  }
};

function mapStateToProps(state) {
  return {
    
  }
}

function mapDispatchToProps(dispatch) {
  return {
    removeAllProps: bindActionCreators(removeAllProps, dispatch),
  }
}

/**
 * Higher-order component (HOC) to wrap restricted pages
 */
export default function authHOC(BaseComponent,profile) {
  class Restricted extends Component {
    componentWillMount() {
      this.checkAuthentication(this.props);
    }
    componentWillReceiveProps(nextProps) {
      if (nextProps.location !== this.props.location) {
        this.checkAuthentication(nextProps);
      }
    }
    checkAuthentication(params) {
      const { history } = params;
      validate(history);
    }
    render() {
      this.props.removeAllProps();

      if(profile.user)
        return <BaseComponent {...this.props} profile={profile}/>;
      else
        return <div></div>
    }
  }
  
  return withRouter(connect(mapStateToProps, mapDispatchToProps)(Restricted));
}
